package com.bkrebs.moneybud;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;

import com.googlecode.jcsv.reader.CSVReader;
import com.googlecode.jcsv.reader.internal.CSVReaderBuilder;

public class ImportFrame extends JFrame {
	GUI myGui;

	public ImportFrame(GUI gui) {
		super("Importieren");
		myGui = gui;
		setSize(300, 200);
		setLocationRelativeTo((JFrame) gui);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

		setLayout(new BorderLayout(5, 5));

		JPanel panel = new JPanel(new GridLayout(4, 1));

		JButton btImport = new JButton("Dateien importieren");
		btImport.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				File myFile = selectFile();
				if (myFile != null)
					parseCSV(myFile);
			}
		});

		panel.add(btImport);

		getContentPane().add(panel);

		setVisible(true);
	}

	private File selectFile() {
		File myFile = null;
		JFileChooser fc = new JFileChooser(
				"C:\\Dokumente und Einstellungen\\Krebs\\Desktop");
		fc.setFileFilter(new FileFilter() {
			@Override
			public boolean accept(File f) {
				return f.isDirectory()
						|| f.getName().toLowerCase().endsWith(".csv");
			}

			@Override
			public String getDescription() {
				return "Bankdaten | *.csv";
			}
		});
		int state = fc.showOpenDialog(null);
		if (state == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			// System.out.println(file.getAbsolutePath());
			myFile = file;
		} else
			System.out.println("Auswahl abgebrochen");

		return myFile;
	}

	private void parseCSV(File myFile) {
		Reader reader = null;
		List<String[]> data = null;
		try {
			reader = new FileReader(myFile.getAbsoluteFile());
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		CSVReader<String[]> csvParser = CSVReaderBuilder
				.newDefaultReader(reader);
		try {
			data = csvParser.readAll();

		} catch (IOException e) {
			e.printStackTrace();
		}

		if (data != null) { // daten kategorisieren
			String cat = data.get(0)[0];
			short mode = -1;

			if (cat.equals("Auftragskonto")) {
				System.out.println(data.size() + " SPK");
				mode = 0;

			} else if (cat.equals("Kreditkarte:")) {
				System.out.println(data.size() + " DKB");
				mode = 1;

			} else {
				System.out.println(data.size() + " AMEX");
				mode = 2;
			}
			Main.myDB.includeData(data, mode);
		}

	}

	@Override
	public void dispose() {
		myGui.actualize();
		super.dispose();
	}
}
